package com_fit.springboot_fit.service.impl;

import com_fit.springboot_fit.entity.AdminPower;
import com_fit.springboot_fit.repository.AdminPowerRepository;
import com_fit.springboot_fit.service.AdminPowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AdminPowerServiceImpl implements AdminPowerService {

    @Autowired
    private AdminPowerRepository powerRepository;

    @Override
    @Transactional
    public AdminPower save(AdminPower power) {
        if (power.getId() == null) {
            power.setAddTime(new Date());
        }
        return powerRepository.save(power);
    }

    @Override
    @Transactional
    public List<AdminPower> saveAll(List<AdminPower> powers) {
        Date now = new Date();
        for (AdminPower power : powers) {
            if (power.getId() == null) {
                power.setAddTime(now);
            }
        }
        return powerRepository.saveAll(powers);
    }

    @Override
    @Transactional
    public void deleteByUid(Integer uid) {
        powerRepository.deleteByUid(uid);
    }

    @Override
    @Transactional
    public void deleteByGid(Integer gid) {
        powerRepository.deleteByGid(gid);
    }

    @Override
    @Transactional
    public void assignUserPermissions(Integer uid, List<Integer> menuIds) {
        // 先删除用户原有的所有权限
        deleteByUid(uid);

        // 如果没有选择任何菜单，直接返回
        if (menuIds == null || menuIds.isEmpty()) {
            return;
        }

        // 创建新的权限列表
        List<AdminPower> powers = new ArrayList<>();
        for (Integer mid : menuIds) {
            AdminPower power = new AdminPower();
            power.setUid(uid);
            power.setMid(mid);
            // 用户权限的gid设为0，表示是用户自身的权限
            power.setGid(0);
            power.setAddTime(new Date());
            powers.add(power);
        }

        // 保存新权限
        saveAll(powers);
    }

    @Override
    @Transactional
    public void assignGroupPermissions(Integer gid, List<Integer> menuIds) {
        // 先删除用户组原有的所有权限
        deleteByGid(gid);

        // 如果没有选择任何菜单，直接返回
        if (menuIds == null || menuIds.isEmpty()) {
            return;
        }

        // 创建新的权限列表
        List<AdminPower> powers = new ArrayList<>();
        for (Integer mid : menuIds) {
            AdminPower power = new AdminPower();
            // 用户组权限的uid设为0，表示是用户组的权限
            power.setUid(0);
            power.setGid(gid);
            power.setMid(mid);
            power.setAddTime(new Date());
            powers.add(power);
        }

        // 保存新权限
        saveAll(powers);
    }
}
